package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.config.ThreadPoolConfig;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 确认订单
     *
     * @param request
     * @return
     */
    @GetMapping("auth/trade")
    public Result<Map<String, Object>> trade(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String userId = AuthContextHolder.getUserId(request);
        //获取用户地址
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        // 渲染送货清单
        // 先得到用户想要购买的商品！
//        根据用户Id 查询购物车列表
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        List<OrderDetail> detailArrayList = new ArrayList<>();
        for (CartInfo cartInfo : cartCheckedList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            detailArrayList.add(orderDetail);
        }
        map.put("userAddressList", userAddressList);
        map.put("detailArrayList", detailArrayList);
        // 保存总金额,计算完成之后赋值给当前对象 totalAmount
        map.put("totalNum", cartCheckedList.size());
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailArrayList);
        orderInfo.sumTotalAmount();
        map.put("totalAmount", orderInfo.getTotalAmount());
        String tradeNo = orderService.getTradeNo(userId);
        map.put("tradeNo", tradeNo);

        return Result.ok(map);
    }

    /**
     * 提交订单
     *
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);

        String tradeNo = request.getParameter("tradeNo");

        boolean tradeCode = orderService.checkTradeCode(userId, tradeNo);
        if (!tradeCode) {
            // 比较失败！
            return Result.fail().message("不能重复提交订单！");
        }
        //删除缓存流水号
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        List<String> stringList = new ArrayList<>();
        List<CompletableFuture> completableFutures = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            //验证库存
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {

                boolean checkStock = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                if (!checkStock) {
                    stringList.add(orderDetail.getSkuName() + "库存不足！");
//                    Result.fail().message(orderDetail.getSkuName() +"库存不足！");
                }
            }, threadPoolExecutor);
            completableFutures.add(voidCompletableFuture);
            //验证价格
            CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                BigDecimal orderPrice = orderDetail.getOrderPrice();
                BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                if (orderPrice.compareTo(skuPrice) != 0) {
                    //价格有变动,更改购物车价格
                    cartFeignClient.loadCartCache(userId);
                    stringList.add(orderDetail.getSkuName() + "价格有变动！");
                }
            }, threadPoolExecutor);
            completableFutures.add(priceCompletableFuture);

            //验证商品的价格
//
//            BigDecimal orderPrice = orderDetail.getOrderPrice();
//
//            BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
//            if (orderPrice.compareTo(skuPrice) != 0){
//                //价格有变动,更改购物车价格
//                cartFeignClient.loadCartCache(userId);
//                return Result.fail().message(orderDetail.getSkuName() + "价格有变动！");
//            }
//        }
//            orderService.deleteTradeNo(userId);

        }
        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()])).join();
        if (stringList.size() > 0) {
            return Result.fail().message(StringUtils.join(stringList, ","));
        }
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return Result.ok(orderId);
    }

    /**
     * 内部调用获取订单，根据订单Id 查询订单信息
     * @param orderId
     * @return
     */
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable(value = "orderId") Long orderId){
        return orderService.getOrderInfo(orderId);
    }

    //  拆单的数据接口！
    //  http://localhost:8204/api/order/orderSplit?orderId=xxx&wareSkuMap=xxx
    @PostMapping("orderSplit")
    public String orderSplit(HttpServletRequest request){
        //  获取到订单Id
        String orderId = request.getParameter("orderId");
        //  仓库Id 与 商品skuId 的对照关系 [{"wareId":"1","skuIds":["2","10"]},{"wareId":"2","skuIds":["3"]}]
        String wareSkuMap = request.getParameter("wareSkuMap");

        //  声明一个集合来存储map
        ArrayList<Map> maps = new ArrayList<>();
        //  先根据上述两个参数得到子订单集合：
        List<OrderInfo> orderInfoList = orderService.orderSplit(orderId,wareSkuMap);

        for (OrderInfo orderInfo : orderInfoList) {
            //  orderInfo 转换的map 集合
            Map map = orderService.initWareOrder(orderInfo);
            maps.add(map);

        }
        return JSON.toJSONString(maps);
    }
    /**
     * 秒杀提交订单，秒杀订单不需要做前置判断，直接下单
     * @param orderInfo
     * @return
     */
    @PostMapping("inner/seckill/submitOrder")
    public Long submitOrder(@RequestBody OrderInfo orderInfo) {
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return orderId;
    }

}
